package com.csu.tingtian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csu.tingtian.common.CommonResponse;
import com.csu.tingtian.common.ResponseCode;
import com.csu.tingtian.entity.Account;
import com.csu.tingtian.entity.LegalFarm;
import com.csu.tingtian.entity.SignOn;
import com.csu.tingtian.entity.UnDeterminedFarms;
import com.csu.tingtian.persistence.AccountMapper;
import com.csu.tingtian.persistence.LegalFarmMapper;
import com.csu.tingtian.persistence.SignOnMapper;
import com.csu.tingtian.persistence.UnDeterminedFarmsMapper;
import com.csu.tingtian.service.AccountService;
import com.csu.tingtian.utils.TokenUtil;
import com.csu.tingtian.vo.Business;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service("accountService")
public class AcountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private SignOnMapper signOnMapper;
    @Autowired
    private LegalFarmMapper legalFarmMapper;
    @Autowired
    private UnDeterminedFarmsMapper unDeterminedFarmsMapper;
    @Autowired
    @Qualifier("redisTemplateCustomize")
    private RedisTemplate redisTemplate ;

    private Account account = null;
    private SignOn signOn = null;
    private LegalFarm legalFarm = null;

    //根据用户名获取用户信息
    @Override
    public CommonResponse<Account> getAccount(String username) {
        account = accountMapper.selectById(username);
        return CommonResponse.createForSuccess(account);
    }

    //根据用户名和密码获取用户
    @Override
    public CommonResponse<Account> getAccount(String username, String password) {
        signOn = signOnMapper.selectById(username);

        LoggerFactory.getLogger(AcountServiceImpl.class).info("你爸爸来请求你啦！！");

        //若存在该用户
        if(signOn!=null) {
            //若密码正确
            if(signOn.getUserPassword().equals(password)) {
                account = accountMapper.selectById(username);
                //密码正确，即登录成功，那么生成token，与其他数据一并发送给前端
                String token = TokenUtil.sign(username,password);
                //并且存入Redis
                redisTemplate.opsForValue().set( token,username, 10, TimeUnit.MINUTES);
                return CommonResponse.createForToken(token,"登录成功",account);
            }
            else
                return CommonResponse.createForError(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"密码错误");
        }
        else
            return CommonResponse.createForError(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"不存在该用户");
    }

    //根据手机号获取用户信息
    @Override
    public CommonResponse<Account> getAccountByPhone(String phone) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        account = accountMapper.selectOne(queryWrapper.eq("phoneNum",phone));
        if(account!=null) {
            return CommonResponse.createForSuccess(account);
        }
        else
            return CommonResponse.createForError("用户不存在");
    }

    //插入一个用户到数据库
    @Override
    public CommonResponse<Account> insertAccount(Account account) {
        signOn = new SignOn();
        signOn.setUserPassword(account.getUserPassword());
        signOn.setUserName(account.getUserName());

        int i = signOnMapper.insert(signOn);
        int m = accountMapper.insert(account);

        if(i > -1 && m > -1)
            return CommonResponse.createForSuccess("插入成功",account);
        else
            return CommonResponse.createForError(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"插入失败");
    }

    //更新用户信息
    @Override
    public CommonResponse<Account> updateAccount(Account accountt) {
        signOn = signOnMapper.selectById(accountt.getUserName());

        account = accountMapper.selectById(accountt.getUserName());


        if(!accountt.getDescription().equals(account.getDescription())) {
            account.setDescription(accountt.getDescription());
        }
        if(accountt.getUserAddress() != "") {
            account.setUserAddress(accountt.getUserAddress());
        }
        if(!accountt.getUserEmail().equals(account.getUserEmail())) {
            account.setUserEmail(accountt.getUserEmail());
        }
        //
        if(accountt.getUserPhoneNum() != "") {
            account.setUserPhoneNum(accountt.getUserPhoneNum());
        }
        if(accountt.getUserPassword() != "") {
            account.setUserPassword(accountt.getUserPassword());
            signOn.setUserPassword(accountt.getUserPassword());
        }


        int i = signOnMapper.updateById(signOn);
        int m = accountMapper.updateById(account);

        if(i > -1 && m > -1)
            return CommonResponse.createForSuccess("更新成功",account);
        else
            return CommonResponse.createForError(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"更新失败");
    }

    //判断是否已存在该用户
    @Override
    public CommonResponse<String> isExit(String username) {
        account = accountMapper.selectById(username);
        if(account != null)
            return CommonResponse.createForError(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"用户名已存在");

        else
            return CommonResponse.createForSuccess();
    }

    //返回用户类型
    @Override
    public CommonResponse<String[]> getIdentity(String username) {
        //先在总的用户表中找出这个人
        account = accountMapper.selectById(username);

        //再从legalfarm中找，看这个人是不是商家
        QueryWrapper<LegalFarm> queryWrapper = new QueryWrapper<>();
        legalFarm = legalFarmMapper.selectOne(queryWrapper.eq("username",username));

        String[] roles = new String[1];

        //若account不为空，legalFarm为空，说明这个人是普通用户
        if(account != null && legalFarm == null) {
            roles[0] = "admin";
            return CommonResponse.createForRoles(roles);
        }
        else if(account != null && legalFarm != null) {
            roles[0] = "editor";
            return CommonResponse.createForRoles(roles);
        }
        else
            return CommonResponse.createForError(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"用户名错误");
    }

    //获取所有用户
    @Override
    public CommonResponse<List<Account>> getAllAccount() {
        List<Account> list = accountMapper.selectList(null);

        return CommonResponse.createForSuccess(list);
    }

    //插入一条记录到underminedfarm
    @Override
    public CommonResponse<UnDeterminedFarms> insertUndeterminedFarm(UnDeterminedFarms unDeterminedFarms) {
        unDeterminedFarmsMapper.insert(unDeterminedFarms);
        return CommonResponse.createForSuccess("插入成功",unDeterminedFarms);
    }

    //若该用户的商家，获取个人信息和他的农场信息
    @Override
    public CommonResponse<Business> getBusiness(String userName) {
        //获取个人信息
        account = accountMapper.selectById(userName);
        //获取农场信息
        QueryWrapper<LegalFarm> queryWrapper = new QueryWrapper<>();
        legalFarm = legalFarmMapper.selectOne(queryWrapper.eq("userName",userName));

        //合并到business
        Business business = new Business();
        business.setUserName(account.getUserName());
        business.setUserPassword(account.getUserPassword());
        business.setUserEmail(account.getUserEmail());
        business.setUserAddress(account.getUserAddress());
        business.setUserPhoneNum(account.getUserPhoneNum());
        business.setDescription(account.getDescription());

        business.setFarmName(legalFarm.getFarmName());
        business.setFarmAddress(legalFarm.getFarmAddress());
        business.setFarmCertificateNum(legalFarm.getFarmCertificateNum());
        business.setFarmFreeArea(legalFarm.getFarmFreeArea());
        business.setFarmTotalArea(legalFarm.getFarmTotalArea());
        business.setIsRent(legalFarm.getIsRent());
        return CommonResponse.createForSuccess(business);
    }
}
